// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;

namespace SnapObjects.Data
{
    internal abstract class SqlInsertStatementGenerator : SqlStatementGenerator
    {
        public SqlInsertStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        protected override IReadOnlyList<SqlToken> SpliceStatement(SqlStatement statement)
        {
            var result = new List<SqlToken>();

            var insert = (SqlInsertStatement)statement;

            this.ParseInsertInto(result, insert);

            this.ParseInsertValues(result, insert);

            this.ParseInsertTerminator(result, insert);

            return result;
        }

        protected virtual void ParseInsertInto(List<SqlToken> tokens, SqlInsertStatement insert)
        {
            tokens.Add(new SqlKeywordToken(SqlKeywords.INSERT));
            tokens.Add(SqlWhitespaceToken.Whitespace);
            tokens.Add(new SqlKeywordToken(SqlKeywords.INTO));
            tokens.Add(SqlWhitespaceToken.Whitespace);
            tokens.AddRange(this.SpliceClause(insert.Table));

            if (insert.Into.Count > 0)
            {
                tokens.Add(new SqlCharacterToken(SqlCharacters.OpenParentheses));
                tokens.AddRange(this.SpliceClause(insert.Into));
                tokens.Add(new SqlCharacterToken(SqlCharacters.CloseParentheses));
            }

            tokens.Add(SqlWhitespaceToken.Whitespace);
        }

        protected virtual void ParseInsertValues(List<SqlToken> tokens, SqlInsertStatement insert)
        {
            tokens.Add(new SqlKeywordToken(SqlKeywords.VALUES));
            tokens.Add(new SqlCharacterToken(SqlCharacters.OpenParentheses));
            tokens.AddRange(this.SpliceClause(insert.Values));
            tokens.Add(new SqlCharacterToken(SqlCharacters.CloseParentheses));
        }

        protected virtual void ParseInsertTerminator(List<SqlToken> tokens, SqlInsertStatement insert)
        {
            tokens.Add(SqlWhitespaceToken.Whitespace);
            tokens.AddRange(this.SpliceClause(insert.Terminator));
        }
    }
}
